﻿using System.Data.Entity;
using TinyContactManager.Web.Internal.Entities;

namespace TinyContactManager.Web.Internal.Data
{
    public class ContactsEngineContext : DbContext, IDbContext
    {
        public ContactsEngineContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }

        public ContactsEngineContext()
        {
        }

        public DbSet<Contact> Contacts { get; set; }
        public DbSet<Address> Addresses { get; set; }
        public DbSet<Mailing> Mailings { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var model = modelBuilder.Entity<Contact>();
            model.HasKey(x => x.Id);
            model.HasRequired(x => x.PostalAddress).WithMany(x => x.Contacts);
            model.HasMany(x => x.Mailings).WithRequired(x => x.Contact).HasForeignKey(x => x.Contact_Id);

            var address = modelBuilder.Entity<Address>();
            address.HasKey(x => x.Id);

            var mailing = modelBuilder.Entity<Mailing>();
            mailing.HasKey(x => x.Id);

            base.OnModelCreating(modelBuilder);
        }

        IDbSet<TEntity> IDbContext.Set<TEntity>()
        {
            return Set<TEntity>();
        }

        public void Save()
        {
            SaveChanges();
        }
    }
}